﻿using System;
using System.Net;

namespace BloggerAutoPosterService.Engine.Net
{
    public class RedirectFinder : IRedirectFinder
    {
        #region Properties (2)

        public CookieContainer Cookies { set; get; }

        public string Url { get; set; }

        #endregion Properties

        #region Methods (1)

        // Public Methods (1) 

        public string GetRedirectUrl()
        {
            var hops = 1;
            const int maxRedirects = 20;

            do
            {
                var request = (HttpWebRequest)WebRequest.Create(Url);
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
                request.KeepAlive = true;                
                request.Referer = Url;
                if (Cookies == null) Cookies = new CookieContainer();
                request.CookieContainer = Cookies;
                request.AllowAutoRedirect = false;

                using (var webResp = request.GetResponse() as HttpWebResponse)
                {
                    if ((webResp.StatusCode == HttpStatusCode.Found) ||
                    (webResp.StatusCode == HttpStatusCode.Redirect) ||
                    (webResp.StatusCode == HttpStatusCode.Moved) ||
                    (webResp.StatusCode == HttpStatusCode.MovedPermanently))
                    {
                        var newLocation = webResp.Headers["Location"];
                        if (newLocation.StartsWith("/"))
                        {
                            var uri = new Uri(Url);
                            Url = string.Format("{0}://{1}:{2}{3}", uri.Scheme, uri.Host, uri.Port, newLocation);
                        }
                        else
                            Url = newLocation;
                    }
                    else
                    {
                        if (webResp.StatusCode == HttpStatusCode.OK)
                            return Url;
                    }
                }

                hops++;
            } while (hops <= maxRedirects);
            return Url;
        }

        #endregion Methods
    }
}
